package com.zyl.blog.common.enums;

import com.zyl.blog.common.utils.Extreme.LogUtil;
import lombok.Getter;

import java.util.Arrays;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @version v1.0
 * @ProjectName: Personal_Blog
 * @Package: com.zyl.common.core.enums
 * @ClassName: DataScope
 * @Description:
 * @Author FinalFantasy
 * @Date 2025/2/18-15:08
 */
@Getter
public enum DataScope {

    ALL(0, "全部数据", "可访问所有数据（含跨部门）"),
    CURRENT_DEPT(1, "本部门及子部门", "仅能访问所属部门及下级部门数据"),
    CURRENT(2, "本部门", "仅能访问所属部门数据"),
    CUSTOM(3, "自定义", "根据配置的部门ID列表限制访问范围"),
    SELF(4, "个人", "仅能访问自己创建的数据");

    private final int code;
    private final String shortDesc;
    private final String fullDesc;

    private static final Map<Integer, DataScope> CODE_MAP = Arrays.stream(values())
            .collect(Collectors.toMap(DataScope::getCode, Function.identity()));

    DataScope(int code, String shortDesc, String fullDesc) {
        this.code = code;
        this.shortDesc = shortDesc;
        this.fullDesc = fullDesc;
    }

    /**
     * 根据编码获取枚举实例（企业级防御性实现）
     *
     * @param code 数据权限编码
     * @return 对应的枚举实例
     * @throws IllegalArgumentException 当传入无效编码时抛出
     */
    public static DataScope getByCode(int code) {
        DataScope scope = CODE_MAP.get(code);
        if (scope == null) {
            throw new IllegalArgumentException("无效的数据权限编码: " + code);
        }
        return scope;
    }

    /**
     * 获取前端展示的简洁描述
     */
    public static String getDescByCode(Integer code) {
        if (code == null) return "未知";
        try {
            return getByCode(code).getShortDesc();
        } catch (IllegalArgumentException e) {
            LogUtil.warn("遇到未知数据权限编码: {}", code);
            return "未知范围";
        }
    }

    /**
     * 校验是否为有效编码（防御非法参数）
     */
    public static boolean isValidCode(Integer code) {
        if (code == null) return false;
        return CODE_MAP.containsKey(code);
    }
}